import {createRouter, createWebHashHistory} from 'vue-router'
import {setupLayouts} from 'virtual:generated-layouts'
import generatedRoutes from 'virtual:generated-pages'
import {checkStatusAction, configListAction, $response} from "~/api"
import {reGetAdmin} from "~/tool/info"
import {
    useStore, usePages, useAccount, useSaveTokenType, useSessionToken, useToken, useRouterActive
} from '~/store'

const no_login_list = ['login', '404'];

const $pages = usePages()
const $account = useAccount()
const $router_active = useRouterActive()
const router = createRouter({
    history: createWebHashHistory(import.meta.env.BASE_URL), routes: setupLayouts(generatedRoutes)
})

const updatePages = (to) => {
    const $store = useStore()
    const account = $account.value.account
    if (!(account in $pages.value) || $pages.value[account].length === 0) {
        $pages.value[account] = [{
            title: $store.config.title, key: 'index', path: '/', disabled: false
        }]
    }
    $pages.value[account][0].title = $store.config.title
    let has = -1
    for (let i in $pages.value[account]) {
        if ($pages.value[account][i].key === to.name) {
            has = i
            $pages.value[account][i].path = to.fullPath
            if (to.name !== 'index') {
                $pages.value[account][i].title = 'title' in to.meta ? to.meta.title : to.name
            }
            $pages.value[account][i].disabled = false
        } else {
            $pages.value[account][i].disabled = true
        }
    }
    if (to.name !== 'index') {
        if (has === -1) {
            $pages.value[account].push({
                title: 'title' in to.meta ? to.meta.title : to.name, key: to.name, path: to.fullPath, disabled: false
            })
        }
    } else {
        $pages.value[account][0].active = true
        $pages.value[account][0].disabled = false
    }
}

const updateRouterActive = (matched) => {
    matched.shift()
    const last = matched[matched.length - 1]
    if (no_login_list.indexOf(last.name) !== -1) return $router_active.value = []
    $router_active.value = matched.map((item) => {
        return {
            title: 'title' in item.meta ? item.meta.title : item.name,
            icon: 'icon' in item.meta ? item.meta.icon : false,
            key: item.name
        }
    })
}

router.beforeEach(async (to, from, next) => {
    window.$loading.start()
    const $store = useStore()
    if (!$store.config) {
        const response = await configListAction()
        $response(response, () => {
            $store.config = response.data
        })
    }
    document.title = ('title' in to.meta && to.meta.title !== '首页') ? `${to.meta.title} ${$store.config.title}` : $store.config.title
    if (no_login_list.indexOf(to.name) === -1) {
        const $save_token_type = useSaveTokenType()
        let $token;
        if ($save_token_type.value === 'local') {
            $token = useToken()
        } else {
            $token = useSessionToken()
        }
        if ($token.value === '') {
            next('/login?f=' + encodeURIComponent(to.fullPath))
            setTimeout(() => {
                window.$loading.finish()
            })
        } else {
            const response = await checkStatusAction()
            $response(response, () => {
                if (!$store.admin_info) reGetAdmin()
                updateRouterActive(to.matched.map(item => item))
                updatePages(to)
                next()
            }, next)
            setTimeout(() => {
                window.$loading.finish()
            })
        }
    } else {
        next()
        setTimeout(() => {
            window.$loading.finish()
        })
    }
})
export default router
